package com.tihi.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 执行shell命令
 * @author duantihi
 *
 * @date 2016-1-31 下午5:13:19
 */
public class ShellCommand {
	
	public static String execCmd(String cmd, boolean haveOutStream) {
		String result = null;
		Runtime mRuntime = Runtime.getRuntime();
		DataOutputStream os = null;
		try {
			// 用 su 用户身份执行命令 才有效, su 是在访问限制权限时才需要
			Process mProcess = mRuntime.exec("sh");
//			Process mProcess = mRuntime.exec(cmd);
			os = new DataOutputStream(mProcess.getOutputStream());
			os.writeBytes(cmd + "\n");
			os.writeBytes("exit\n"); // 必须加这句，否则卡住
			os.flush();
			mProcess.waitFor();

			if (haveOutStream) { // 没有输出则不读取，否则会被卡住
				BufferedReader mReader = new BufferedReader(
						new InputStreamReader(mProcess.getInputStream()));
				StringBuffer mRespBuff = new StringBuffer();
				char[] buff = new char[1024];
				int ch = 0;
				while ((ch = mReader.read(buff)) != -1) {
					mRespBuff.append(buff, 0, ch);
				}
				mReader.close();
				result = mRespBuff.toString();
			}
			LogUtil.log("exec shell over: " + cmd + ", out: " + result);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return result;
	}
}
